<?php

namespace app\common\event;

use app\api\library\Auth;
use app\common\model\Shop;
use app\common\model\ShopOrder;
use app\common\model\ShopSkus;
use think\facade\Log;
use think\Request;
use Throwable;

class CancelOrder
{

    public function handle(Request $request)
    {
        $auth = Auth::instance();
        $ids = $request->param('ids');
        // $where[] = ['status', '=', 0]; //待付款状态
        $where[] = ['id', 'in', $ids];
        $where[] = ['user_id', '=', $auth->id];
        try {
            $data  = ShopOrder::with(['shopOrderSku'])->where($where)->select()->toArray();
            foreach ($data as $v) {
                $shop = Shop::where('id', '=', $v['shopOrderSku']['shop_id'])->lock(true)->find();
                $shopSku = ShopSkus::where('id', $v['shopOrderSku']['shop_skus_id'])->lock(true)->find();
    
                if ($shop->specs == 0) {
                    if ($shop->stock > 0) {
                        $shop->stock += $v['total_num'];
                        $shop->save();
                    }
                } else {
                    if ($shopSku->stock > 0) {
                        $shopSku->stock +=$v['total_num'];
                        $shopSku->save();
                    }
                }
            }
        } catch (Throwable $e) {
            Log::record('[ CancelOrder ]' . $e->getMessage(), 'warning');
        }
        return true;
    }
}
